#!/usr/bin/env python3

import time
import random
from multiprocessing import pool, Queue, Manager

class BlockingPool(pool.Pool):
    def _setup_queues(self):
        pool.Pool._setup_queues(self)
        self._taskqueue = Queue(2)
        self._inqueue = Queue(2)
        self._quick_put = self._inqueue.put

def feedqueue(func, queue):
    return func(queue.get())

def procfunc(num):
    time.sleep(random.random() * 2)
    return num * 2

def printrange(n):
    for i in range(n):
        print("generated " + str(i))
        yield i

def oldmain():
    sm = Manager() 
    #sm.start()
    pool = Pool()
    queuelen = len(pool._pool) * 2
    queue = sm.Queue(queuelen)
    for i in printrange(100):
        queue.put(i)
        pool.apply_async(procfunc, (queue,), callback=print)
    pool.close()
    pool.join()

def newmain():
    pool = BlockingPool()
    print("Processes: " + str(len(pool._pool)))
    pool.map_async(procfunc, printrange(25), 1, print)
    #for i in printrange(25):
    #    pool.apply_async(procfunc, (i,), callback=print)
    pool.close()
    pool.join()

if __name__ == "__main__":
    exit(newmain())
